package com.mrd.shiptask_shipowner.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.mrd.shiptask_shipowner.R;
import com.mrd.shiptask_shipowner.constants.HttpConstant;
import com.mrd.shiptask_shipowner.constants.PortUtil;
import com.mrd.shiptask_shipowner.constants.database.DBUtil;
import com.mrd.shiptask_shipowner.serviecs.BizNetworkService;
import com.mrd.shiptask_shipowner.shiareutil.SharePreferenceUtil;
import com.mrd.shiptask_shipowner.unit_tools.HttpUrlConstant;
import com.mrd.shiptask_shipowner.unit_tools.SysApplication;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class PortMnuActivity extends Activity {
	private final PortMnuActivity THIS = PortMnuActivity.this;
	private SharePreferenceUtil sp;
	private GridView gridView;
	ArrayList<HashMap<String, Object>> meumList;
	private EditText searchEt;
	ProgressDialog progressDialog;
	ProgressDialog progressDialog1;
	private boolean actionOver = false;
	private Button quedingBt;
	private ListView listView1;
	private Button guangdongBt, guangxiBt, xianggangBt, aomenBt;
	// spinner显示那组数据的标识，未选择为0，广东省份为1，广西省份为2
	private int showCitysTap = 0;
	private List<Map<String, Object>> mData;
	private MyAdapter adapter;
	// 广东 市
	static String[] guangdongCitys = new String[] { "广州", "深圳", "珠海", "汕头",
			"韶关", "佛山", "江门", "湛江", "茂名", "肇庆", "惠州", "梅州", "汕尾", "河源", "阳江",
			"清远", "东莞 ", "中山 ", "潮州", "揭阳 ", "云浮" };
	static String[] guangxiCitys = { "南宁", "桂林", "柳州", "梧州", "钦州", "北海", "玉林",
			"贵港", "防城港", "百色", "崇左", "来宾", "贺州", "河池" };
	static String[] xianggangCitys = { "香港岛", "九龙", "新界" };
	static String[] aomenCitys = { "澳门半岛", "澳门离岛" };
	static String[] qingxuanzeCity = { "广州", "深圳", "珠海", "汕头", "韶关", "佛山",
			"江门", "湛江", "茂名", "肇庆", "惠州", "梅州", "汕尾", "河源", "阳江", "清远", "东莞 ",
			"中山 ", "潮州", "揭阳 ", "云浮", "南宁", "桂林", "柳州", "梧州", "钦州", "北海", "玉林",
			"贵港", "防城港", "百色", "崇左", "来宾", "贺州", "河池", "香港岛", "九龙", "新界",
			"澳门半岛", "澳门离岛" };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.port_mnu_list);
		sp = new SharePreferenceUtil(THIS, HttpConstant.SAVE_USER);
		progressDialog = new ProgressDialog(THIS);
		progressDialog1 = new ProgressDialog(THIS);

		initPortAction();
		setViewAction();
		initListView(showCitysTap);
		try {
			JSONArray jas = DBUtil.selectPorts(THIS);
			setGridViewAction(jas);
		} catch (Exception e) {
		}
		SysApplication.getInstance().addActivity(this);
	}

	private void initListView(int showCitysTap) {
		// TODO Auto-generated method stub
		try {

			listView1 = (ListView) findViewById(R.id.portlistView);
			// 生成动态数组，并且转入数据
			switch (showCitysTap) {
			case 0:
				mData = PortUtil.getCitysBySheng(qingxuanzeCity);
				break;
			case 1:
				mData = PortUtil.getCitysBySheng(guangdongCitys);
				break;
			case 2:
				mData = PortUtil.getCitysBySheng(guangxiCitys);
				break;
			case 3:
				mData = PortUtil.getCitysBySheng(xianggangCitys);
				break;
			case 4:
				mData = PortUtil.getCitysBySheng(aomenCitys);
				break;
			default:
				break;
			}
			// 生成适配器的ImageItem <====> 动态数组的元素，两者一一对应
			adapter = new MyAdapter(THIS);
			listView1.setAdapter(adapter);
		} catch (Exception e) {
		}
	}

	private void initPortAction() {
		// 加载gridview
		if (!sp.getIsGetDataOfPorts()) {
			progressDialog.setMessage("正在加载，请稍后···");
			progressDialog.show();

			new Thread(new BizNetworkService(THIS, handler,
					HttpUrlConstant.INIT_PORTS_JSON, null)).start();
		}
	}

	private void setViewAction() {
		gridView = (GridView) findViewById(R.id.Grid_View);
		searchEt = (EditText) findViewById(R.id.search_et);
		searchEt.addTextChangedListener(watcher);
		quedingBt = (Button) findViewById(R.id.quedingbt);
		quedingBt.setOnClickListener(socl);
		guangdongBt = (Button) findViewById(R.id.guangdong);
		guangxiBt = (Button) findViewById(R.id.guangxi);
		xianggangBt = (Button) findViewById(R.id.xianggang);
		aomenBt = (Button) findViewById(R.id.aomen);
		xianggangBt.setOnClickListener(socl);
		aomenBt.setOnClickListener(socl);
		guangdongBt.setOnClickListener(socl);
		guangxiBt.setOnClickListener(socl);
	}

	private final OnClickListener socl = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			switch (arg0.getId()) {
			case R.id.quedingbt:
				Intent intent = new Intent();
				intent.putExtra("infoPort", searchEt.getText().toString());
				setResult(RESULT_OK, intent);
				finish();
				break;
			case R.id.guangdong:
				// 选定广东，并赋值广东所有市到spinner
				searchEt.setText("广东");
				showCitysTap = 1;
				initListView(showCitysTap);
				break;
			case R.id.guangxi:
				searchEt.setText("广西");
				showCitysTap = 2;
				initListView(showCitysTap);
				break;
			case R.id.xianggang:
				// 选定广东，并赋值广东所有市到spinner
				searchEt.setText("香港");
				showCitysTap = 3;
				initListView(showCitysTap);
				break;
			case R.id.aomen:
				searchEt.setText("澳门");
				showCitysTap = 4;
				initListView(showCitysTap);
				break;
			default:
				break;
			}

		}
	};
	private final TextWatcher watcher = new TextWatcher() {

		@Override
		public void afterTextChanged(Editable arg0) {
		}

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
		}

		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			String getTextOfInfo;
			// 识别选择是否结束
			if (actionOver) {
				actionOver = false;
				// getTextOfInfo = "";
			} else {
				getTextOfInfo = searchEt.getText().toString();
				JSONArray jas = DBUtil.selectPortByInfoPingYinOrName(THIS,
						getTextOfInfo);
				setGridViewAction(jas);
			}
		}
	};

	private void setGridViewAction(JSONArray jas) {
		progressDialog1.setMessage("正在加载，请稍后···");
		progressDialog1.show();
		// 定义九宫格因素（图标）
		meumList = new ArrayList<HashMap<String, Object>>();
		if (jas.length() > 0) {
			for (int i = 0; i < jas.length(); i++) {
				HashMap<String, Object> map1 = new HashMap<String, Object>();
				String portName;
				try {
					portName = jas.getJSONObject(i).getString("PORT_NAME");
					map1.put("ItemImage", portName);
					meumList.add(map1);
				} catch (JSONException e) {
				}
			}

			progressDialog1.dismiss();
		} else {
			progressDialog1.dismiss();
		}
		SimpleAdapter saItem = new SimpleAdapter(THIS, meumList,
				R.layout.meunitem1, new String[] { "ItemImage" },
				new int[] { R.id.ItemText }); // 对应R的Id

		// 添加Item到网格中
		gridView.setAdapter(saItem);
		// 添加点击事件
		/**
		 * 以下页面跳转在BizNetWorkService中进行，获取到的数据直接赋值到下一页面并进行处理
		 */
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int arg2,
					long arg3) {
				JSONObject job;
				try {
					// 识别选择结束
					actionOver = true;
					job = new JSONObject(meumList.get(arg2).toString());
					searchEt.setText(job.getString("ItemImage"));
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});

	}

	@SuppressLint("HandlerLeak")
	public final Handler handler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			try {
				progressDialog.dismiss();
				Bundle data = msg.getData();
				if (!data.isEmpty()) {
					try {
						sp.setIsGetDataOfPorts(true);
						JSONArray jas = DBUtil.selectPorts(THIS);
						setGridViewAction(jas);
					} catch (Exception e) {

					}
				}
			} catch (Exception e) {
			}
		};
	};

	public final class ViewHolder {
		private TextView portNameTv;
	}

	public class MyAdapter extends BaseAdapter {

		private final LayoutInflater mInflater;

		public MyAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mData.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@SuppressLint({ "NewApi", "ResourceAsColor" })
		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {

			ViewHolder holder = null;

			holder = new ViewHolder();
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.port_listitem, null);
				holder.portNameTv = (TextView) convertView
						.findViewById(R.id.portNameTv);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			try {
				holder.portNameTv.setText(mData.get(position).get("portName")
						.toString());
				holder.portNameTv.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						searchEt.setText(mData.get(position).get("portName")
								.toString());
					}
				});
			} catch (Exception e) {
			}
			return convertView;
		}
	}
}